<script setup lang="ts">
import { ref, reactive } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'

import { getDictAllData } from '@/services/dict'
import { pageStoreAPI } from '@/services/store'
import Avatar from './components/avatar.vue'
import { useStore, useMemberStore, useCategory } from '@/stores'
import { fixResponseEncoding } from '@/utils/http'
import { authInfoAPI, updateDriverAuthInfoAPI } from '@/services/driver'
import type { DeliverymanInfoDTO } from '@/types/driver'
const { getStoreInfo, changeStoreInfo } = useStore()
const { getUserInfo } = useMemberStore()
const { getBuyMethodList, setBuyMethodActiveIndex, getBuyMethodActiveIndex } = useCategory()
const { safeAreaInsets } = uni.getSystemInfoSync()
// 1. 定义表单数据
const formData: DeliverymanInfoDTO = reactive({
  id: getUserInfo()?.id,
  avatarUrl:
    'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132',
  phone: '',
  username: '',
  idcardNo: '',
  idcardAddress: '',
  idcardExpire: '',
  idcardFrontUrl: '',
  idcardBackUrl: '',
  idcardHandUrl: '',
  gender: 0,
  birthday: '',

  // 驾驶证信息（可选）
  driverLicenseNo: '', // 驾驶证号
  driverLicenseExpire: '', // 驾驶证有效期
  driverLicenseIssueDate: '', // 初次领证日期
  driverLicenseFrontUrl: '', // 驾驶证正面
  driverLicenseBackUrl: '', // 驾驶证副页
  driverLicenseHandUrl: '', // 手持驾驶证
  driverLicenseClass: '',
  contactRelationship: '',
  // 紧急联系人
  contactName: '', // 紧急联系人姓名
  contactPhone: '', // 紧急联系人电话
})

const reasonlist = ref([
  {
    text: '不想要了',
    value: 0,
  },
  {
    text: '配送太慢',
    value: 1,
  },
  {
    text: '商品问题',
    value: 2,
  },
  {
    text: '口味不符',
    value: 3,
  },
  {
    text: '重复下单',
    value: 4,
  },
  {
    text: '其他',
    value: 5,
  },
])
const rules: UniHelper.UniFormsRules = {}
const formRef = ref<UniHelper.UniFormsInstance>()

// 4. 提交方法
const submit = async () => {
  const res: any = await formRef.value?.validate?.()
  console.log('表单数据信息：', Object.assign(formData, res))

  await updateDriverAuthInfoAPI(Object.assign(formData, res) as DeliverymanInfoDTO)

  // await applyRefundAPI({
  //   reason: reasonVal,
  //   refundReasonType: res.reason,
  //   orderId: props.orderId,
  //   paymentId: props.paymentId,
  //   type: 1,
  //   userId: getUserInfo().id,
  //   orderStatus: props.orderStatus,
  // })
}
const driverLicenseClassType = ref([] as any[])
const contactNameType = ref([] as any[])
onLoad(async () => {
  driverLicenseClassType.value = ((await getDictAllData('driver_license_class_type')) as any[]).map(
    (item: any) => {
      return { value: item.dictValue, text: item.dictLabel }
    },
  )
  contactNameType.value = ((await getDictAllData('contact_name_type')) as any[]).map(
    (item: any) => {
      return { value: item.dictValue, text: item.dictLabel }
    },
  )

  // 判断是否登录
  if (getUserInfo().id) {
    const authInfo = await authInfoAPI(getUserInfo().id)
    if (authInfo) {
      Object.assign(formData, authInfo.data)
    }
  }

  if (getUserInfo().id) {
    uni.navigateTo({
      url: '/pages/driver/face-model-create?driverId=' + getUserInfo().id,
    })
  }
})
const onAvatarClick = () => {
  console.log('头像被点击')
}

const uploadAvatar = (data: any) => {
  formData.avatarUrl = data.url
}
const uploaOcr = (data: any, type: string) => {
  if (type === 'idcard') {
    if (data.gender) {
      formData.gender = data.gender
    }
    if (data.name) {
      formData.username = fixResponseEncoding(data.name)
    }
    if (data.birthday) {
      formData.birthday = data.birthday
    }
    if (data.idcardAddress) {
      formData.idcardAddress = fixResponseEncoding(data.idcardAddress)
    }
    if (data.idcardNo) {
      formData.idcardNo = data.idcardNo
    }
    if (data.idcardExpire) {
      formData.idcardExpire = data.idcardExpire
    }
    if (data.idcardFrontUrl) {
      formData.idcardFrontUrl = data.idcardFrontUrl
    }
    if (data.idcardBackUrl) {
      formData.idcardBackUrl = data.idcardBackUrl
    }
    if (data.idcardHandUrl) {
      formData.idcardHandUrl = data.idcardHandUrl
    }
  }
  if (type === 'driverLicense') {
    if (data.name) {
      formData.username = fixResponseEncoding(data.name)
    }
    if (data.driverLicenseNo) {
      formData.driverLicenseNo = data.driverLicenseNo
    }
    if (data.driverLicenseExpire) {
      formData.driverLicenseExpire = data.driverLicenseExpire
    }
    if (data.driverLicenseIssueDate) {
      formData.driverLicenseIssueDate = data.driverLicenseIssueDate
    }
    if (data.driverLicenseFrontUrl) {
      formData.driverLicenseFrontUrl = data.driverLicenseFrontUrl
    }
    if (data.driverLicenseBackUrl) {
      formData.driverLicenseBackUrl = data.driverLicenseBackUrl
    }
    if (data.driverLicenseHandUrl) {
      formData.driverLicenseHandUrl = data.driverLicenseHandUrl
    }
    if (data.driverLicenseClass) {
      formData.driverLicenseClass = data.driverLicenseClass
    }
  }
}

const selectdriverLicenseClassOptions = ref([
  { value: '三轮车', text: '三轮车' },
  { value: '电瓶车', text: '电瓶车' },
])

const driverLicenseClassChange = (e: any) => {}
</script>

<template>
  <scroll-view
    scroll-y
    class="deliveryman_info"
    :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }"
  >
    <view class="deliveryman_info_form">
      <uni-forms ref="formRef" :model="formData" :rules="rules">
        <uni-forms-item name="avatarUrl" label="头像">
          <Avatar
            :src="formData.avatarUrl"
            title="上传头像"
            size="normal"
            :round="true"
            @upload="uploadAvatar"
          />
        </uni-forms-item>
        <uni-forms-item name="phone" label="手机号">
          <uni-easyinput v-model="formData.phone" placeholder="手机号" />
        </uni-forms-item>
        <uni-forms-item name="username" label="姓名">
          <uni-easyinput v-model="formData.username" placeholder="姓名" />
        </uni-forms-item>
        <uni-forms-item name="contactName" label="紧急联系人">
          <uni-easyinput v-model="formData.contactName" placeholder="紧急联系人" />
        </uni-forms-item>
        <uni-forms-item name="contactPhone" label="紧急联系人电话">
          <uni-easyinput v-model="formData.contactPhone" placeholder="紧急联系人电话" />
        </uni-forms-item>
        <uni-forms-item name="contactRelationship" label="紧急联系人关系">
          <uni-data-select
            v-model="formData.contactRelationship"
            :localdata="contactNameType"
            @change="driverLicenseClassChange"
          ></uni-data-select>
        </uni-forms-item>
        <uni-forms-item name="idcardFrontUrl" label="身份证正面">
          <Avatar
            :src="formData.idcardFrontUrl"
            size="normal"
            :column="true"
            uploadUrl="/sys/app/ocr/idCardOcr"
            title="上传身份证正面"
            @upload="(data:any) => uploaOcr(data, 'idcard')"
          />
        </uni-forms-item>
        <uni-forms-item name="idcardBackUrl" label="身份证背面">
          <Avatar
            :src="formData.idcardBackUrl"
            size="normal"
            :column="true"
            uploadUrl="/sys/app/ocr/idCardOcr"
            title="上传身份证背面"
            @upload="(data:any) => uploaOcr(data, 'idcard')"
          />
        </uni-forms-item>
        <uni-forms-item name="idcardHandUrl" label="手持身份证">
          <Avatar
            :src="formData.idcardHandUrl"
            size="normal"
            :column="true"
            uploadUrl="/sys/app/ocr/idCardOcr"
            title="手持身份证"
            @upload="(data:any) => uploaOcr(data, 'idcard')"
          />
        </uni-forms-item>

        <!-- 驾驶证信息
        <uni-forms-item name="driverLicenseClass" label="准驾车型">
          <uni-data-select
            v-model="formData.driverLicenseClass"
            :localdata="driverLicenseClassType"
            @change="driverLicenseClassChange"
          ></uni-data-select>
        </uni-forms-item> -->
        <uni-forms-item name="driverLicenseNo" label="驾驶证证件号">
          <uni-easyinput v-model="formData.driverLicenseNo" placeholder="驾驶证证件号" />
        </uni-forms-item>
        <uni-forms-item name="driverLicenseExpire" label="驾驶证有效期">
          <uni-easyinput v-model="formData.driverLicenseExpire" placeholder="驾驶证有效期" />
        </uni-forms-item>
        <uni-forms-item name="driverLicenseIssueDate" label="驾驶证初次领证日期">
          <uni-easyinput
            v-model="formData.driverLicenseIssueDate"
            placeholder="驾驶证初次领证日期"
          />
        </uni-forms-item>
        <uni-forms-item name="driverLicenseFrontUrl" label="驾驶证正面">
          <Avatar
            :src="formData.driverLicenseFrontUrl"
            size="normal"
            :column="true"
            uploadUrl="/sys/app/ocr/driverLicenseOcr"
            title="驾驶证正面"
            @upload="(data:any) => uploaOcr(data, 'driverLicense')"
          />
        </uni-forms-item>
        <uni-forms-item name="driverLicenseBackUrl" label="驾驶证副页正面">
          <Avatar
            :src="formData.driverLicenseBackUrl"
            size="normal"
            :column="true"
            uploadUrl="/sys/app/ocr/driverLicenseOcr"
            title="驾驶证副页正面"
            @upload="(data:any) => uploaOcr(data, 'driverLicense')"
          />
        </uni-forms-item>
        <uni-forms-item name="driverLicenseHandUrl" label="手持驾驶证">
          <Avatar
            :src="formData.driverLicenseHandUrl"
            size="normal"
            :column="true"
            uploadUrl="/sys/app/ocr/driverLicenseOcr"
            title="手持驾驶证"
            @upload="(data:any) => uploaOcr(data, 'driverLicense')"
          />
        </uni-forms-item>

        <!-- 提交按钮 -->
        <view class="submit-button">
          <button class="submit-btn" @click="submit">提交申请</button>
        </view>
      </uni-forms>
    </view>
  </scroll-view>
</template>

<style lang="scss">
@import '@/styles/variables.scss';
page {
  height: 100%;
  overflow: hidden;
  background-color: #fff;
}
.deliveryman_info {
  height: 100%;
  display: flex;
  flex-direction: column;

  .deliveryman_info_form {
    padding: 32rpx;
  }
  .submit-button {
    padding: 32rpx;

    .submit-btn {
      width: 100%;
      height: 96rpx;
      background-color: $color;
      color: white;
      border: none;
      border-radius: 43rpx;
      font-size: $font-medium-size;
      line-height: 96rpx;
      text-align: center;
    }
  }
}
</style>
